package io.renren.common.wechat;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JsapiUtil {

	public static Map<String, String> sign(String jsapiTicket, String url) {
		Map<String, String> ret = new HashMap<>();
		String nonceStr = IdUtil.simpleUUID();
		String timestamp = createTimestamp();

		// 注意这里参数名必须全部小写，且必须有序
		String string1 = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp="
				+ timestamp + "&url=" + url;
		String signature = SecureUtil.sha1(string1);

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapiTicket);
		ret.put("nonceStr", nonceStr);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return ret;
	}

	public static String createTimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}
